package com.wolfpire.system.common.excel2;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wolfpire.system.common.CommonFunctions;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;


public class ExportExcel{

	public static void exportExcel(HttpServletRequest request, HttpServletResponse response, ExcelTable excelTable) {
		try {
			ServletOutputStream outputStream = response.getOutputStream();
			response.reset();// 清空输出流
			if(excelTable!=null) {
				String userAgent = request.getHeader("User-Agent");
				String filename = CommonFunctions.buildFileNameByUa((excelTable.getTableName()+".xls"), userAgent);
				response.setHeader("Content-disposition", ("attachment; " + filename));// 设定输出文件头
				response.setContentType("application/msexcel");// 定义输出类型
				WritableWorkbook workbook = null;
                WorkbookSettings settings = new WorkbookSettings();
                settings.setWriteAccess(null);
                workbook = Workbook.createWorkbook(outputStream, settings);
                WritableSheet wsheet = workbook.createSheet(excelTable.getTableName(), 0);
                for(ExcelCellData data : excelTable.getDataList())
            		wsheet.addCell(new Label(data.getCol(), data.getRow(), data.getValue()));  //列号 行号 值
                //-- 单元格合并
                try {
	                if(excelTable.getMergeCells()!=null && excelTable.getMergeCells().size()>0) {
	                	for(String mc : excelTable.getMergeCells()) {
	                		String[] rowColStr = mc.split(",");
	                		if(rowColStr.length==4)
	                			wsheet.mergeCells(Integer.parseInt(rowColStr[0]), Integer.parseInt(rowColStr[1]), Integer.parseInt(rowColStr[2]), Integer.parseInt(rowColStr[3]));
	                	}
	                }
	                if(excelTable.getColumnWidths()!=null && excelTable.getColumnWidths().size()>0) {
	                	for(String cw : excelTable.getColumnWidths()) {
	                		String[] ColumnWidthStr = cw.split(",");
	                		if(ColumnWidthStr.length==2)
	                			wsheet.setColumnView(Integer.parseInt(ColumnWidthStr[0]), Integer.parseInt(ColumnWidthStr[1]));
	                	}
	                }
                } catch (Exception e) {
                	e.printStackTrace();
                }
                workbook.write();
                workbook.close();
			} else {
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				String content = "<script type='text/javascript'>alert('无数据可导出');window.close();</script>";
				outputStream.write(content.getBytes("UTF-8"));
			}
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}    
    
}
